package com.ly.controller;

import com.ly.bean.Admin;
import com.ly.bean.Menu;
import com.ly.bean.Roles;
import com.ly.service.AdminService;
import com.ly.service.MenuService;
import com.ly.service.RolesService;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 李岩
 * @date 2021/12/27-11:16
 * @describe
 */
@Controller
@RequestMapping("/main/")
public class MainController {
    private final Logger logger= LoggerFactory.getLogger(MainController.class);
    @Reference(url = "dubbo://localhost:20886")
    private AdminService adminService;
    @Reference(url = "dubbo://localhost:20886")
    private RolesService rolesService;
    @Reference(url = "dubbo://localhost:20886")
    private MenuService menuService;

    private MainController(){
        System.out.println("进入了 MainController  controller层");
    }

    @RequestMapping("showMain")
    private String showMain(@CookieValue(required = false) String adminId, Model model, HttpServletRequest request){

        try {
            logger.info("加载管理员的主菜单");
            Admin loginAdmin = adminService.findLoginAdminFromRedis(Integer.valueOf(adminId));
            if (loginAdmin==null){
                model.addAttribute("msg","用户尚未登录");
                return "login";
            }
            //根据用户id获取角色列表
            List<Roles> rolesList = rolesService.selectRoleByaId(loginAdmin.getAId());
            Map<String, Object> map = new HashMap<>();
            map.put("rolesList",rolesList);
            List<Menu> firstMenuList = menuService.findMenuByMap(map);
            Map<Integer, Object> secondMenuMap = new HashMap<>();
            for (Menu menu : firstMenuList) {
                map.put("parentId",menu.getId());
                List<Menu> list = menuService.findMenuByMap(map);
                secondMenuMap.put(menu.getId(),list);
            }

            model.addAttribute("loginAdmin",loginAdmin);
            model.addAttribute("rolesList",rolesList);
            model.addAttribute("firstMenuList",firstMenuList);
            model.addAttribute("secondMenuMap",secondMenuMap);

            return "main_new";
        } catch (Exception e) {
            logger.error("加载管理员的主菜单  出现异常  "+e);
        }
        return "error";
    }
}
